package com.sskj.gcc.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.HttpData;
import com.sskj.gcc.R;
import com.sskj.gcc.component.DaggerUserDataComponent;
import com.sskj.gcc.presenter.PayInFragmentPresenter;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.MoneyValueFilter;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.m.bean.PayInInfoBean;
import com.sskj.gocoin.m.bean.PayWayBean;
import com.sskj.gocoin.mine.VerifyHomeActivity;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.FabiSellDetail2Activity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.activity.VerifyJuniorActivity;
import com.sskj.gocoin.v.activity.WebViewActivity;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppInnerCheckUtil;
import com.sskj.lib.util.TipUtil;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.sskj.gocoin.common.Constants.VERIFY_IDENT_CODE;

@Route(path = RConfig.APP_FRAGMENT_PAY_IN)
public class PayInFragment extends BaseFragment<PayInFragmentPresenter> {

    @BindView(R.id.btn_pay_in_buy)
    Button buyPayInBtn;
    @BindView(R.id.tv_pay_in_price)
    TextView tvPayInPrice;
    @BindView(R.id.tv_pay_in_saler_num)
    TextView tvPayInSalerNum;
    @BindView(R.id.et_fragment_pay_in_money)
    EditText etFragmentPayInMoney;
    @BindView(R.id.tv_fragment_pay_in_num)
    TextView tvFragmentPayInNum;
    Unbinder unbinder;
    @BindView(R.id.ll_fragment_pay_in_pay_type)
    LinearLayout llFragmentPayInPayType;
    @BindView(R.id.security_bottom_recyclerview)
    RecyclerView mSecurityRecyclerView;
    private BaseAdapter<PayWayBean> mAdapter;

    private double price = 0;

    private PayInInfoBean payInInfoBean;

    private String buyNum = "";

    private BottomSheetDialog sellDialog;
    private Button btDeal;

    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    private double minBuy;

    private boolean isEnable;
    private String msg;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pay_in;
    }

    @Override
    protected PayInFragmentPresenter getPresenter() {
        return new PayInFragmentPresenter();
    }

    @Override
    public void initView() {

        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });

        initRecyclerView();

        etFragmentPayInMoney.setFilters(new InputFilter[]{new MoneyValueFilter(2)});

        ClickUtil.click(llFragmentPayInPayType, () -> {
            startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
        });

        ClickUtil.click(buyPayInBtn, () -> {
            payInBuy();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.requsetPayWayList();
    }

    private void initRecyclerView() {
        mSecurityRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mSecurityRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        mAdapter = new BaseAdapter<PayWayBean>(R.layout.layout_pay_way, null, mSecurityRecyclerView) {

            @Override
            public void bind(ViewHolder holder, PayWayBean item) {
                holder.setText(R.id.item_type_name, item.getTip());
                holder.setText(R.id.item_content, String.format("%1$s\t\t%2$s\t\t", item.getName(), item.getNumber()));
                holder.setGone(R.id.item_edit, false);
//                holder.setOnClickListener(com.sskj.gocoin.R.id.item_edit, v -> {//修改支付方式
//                    showDialog(item);
//                });
                holder.setOnClickListener(com.sskj.gocoin.R.id.item_switch, v -> {//切换支付方式开关
                    mPresenter.requsetCheckSwitch(item);
                });
                if (item.getCode() == 0) {
                    holder.setChecked(com.sskj.gocoin.R.id.item_switch, false);
                } else {
                    holder.setChecked(com.sskj.gocoin.R.id.item_switch, true);
                }
                if ("wx".equals(item.getType())) {
                    holder.setImageResource(com.sskj.gocoin.R.id.imageView, com.sskj.gocoin.R.mipmap.icon_wx);
                } else if ("alipay".equals(item.getType())) {
                    holder.setImageResource(com.sskj.gocoin.R.id.imageView, com.sskj.gocoin.R.mipmap.icon_ali);
                } else if ("backcard".equals(item.getType())) {
                    holder.setImageResource(com.sskj.gocoin.R.id.imageView, com.sskj.gocoin.R.mipmap.icon_bank);
                } else if ("paypal".equals(item.getType())) {
                    holder.setImageResource(com.sskj.gocoin.R.id.imageView, com.sskj.gocoin.R.mipmap.pay_pal);
                }
            }
        };
    }

    private void payInBuy() {
//        AppInnerCheckUtil
        if (userData != null) {
            if (checkIdent(getActivity())) {
                if (checkPwdStatus()) {
                    if (TextUtils.isEmpty(etFragmentPayInMoney.getText())) {
                        ToastUtil.showShort(etFragmentPayInMoney.getHint());
                        return;
                    }

                    if (isEnable) {
                        mPresenter.withdraw(etFragmentPayInMoney.getText().toString());
                    } else {
                        if (msg != null) {
                            ToastUtil.showShort(msg);
                        } else {
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.one_buy_maintenance));
                        }
                    }

//                    showSell(payInInfoBean.getOrder_no(), buyNum, etFragmentPayInMoney.getText().toString());
                }
            }
        } else {
            ToastUtil.showShort(App.INSTANCE.getString(com.sskj.gocoin.R.string.strFabiBuyAndSellFragment205));
            ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
            getActivity().overridePendingTransition(com.sskj.gocoin.R.anim.lib_anim_in, com.sskj.gocoin.R.anim.lib_anim_out);

        }
    }

    private void showSell(String oid, String num, String priceStr) {
        sellDialog = new BottomSheetDialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.bottom_sheet_pay_in, null);
        EditText etPayPwd = dialogView.findViewById(R.id.et_pay_in_pwd);
        btDeal = dialogView.findViewById(R.id.bt_pay_in_deal);
        ClickUtil.click(btDeal, () -> {
            if (TextUtils.isEmpty(etPayPwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(com.sskj.gocoin.R.string.fabimineJavaFabiBuyAndSellFragment10));
                return;
            }
            if (!CheckUtil.isPayPwd(etPayPwd.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(com.sskj.gocoin.R.string.strBottomUpUtil201));
                return;
            }
            btDeal.setEnabled(false);
//            mPresenter.order(etPayPwd.getText().toString(),
//                    oid,
//                    NumberUtil.keepNoZore(num),
//                    NumberUtil.keepNoZore(priceStr), userData.getAccount());
        });
        sellDialog.setContentView(dialogView);
        sellDialog.show();
    }

    public void checkOk(String orderNum) {
        sellDialog.dismiss();
        FabiSellDetail2Activity.start(getActivity(), orderNum, true);
    }

    public void setEnable() {
        btDeal.setEnabled(true);
    }

    public boolean checkPwdStatus() {
        if (userData != null) {
            if (userData.getConfig().getPayment_password_set() == 1) {
                return true;
            } else {
                TipUtil.getTip(getActivity(), App.INSTANCE.getString(com.sskj.gocoin.R.string.strMainActivity218), new TipUtil.OnTipSure() {
                    @Override
                    public void onSure() {
                        startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
                    }
                }).show();
                return false;
            }
        }
        return false;
    }

    /**
     * 判断用户初级实名认证
     */
    protected boolean checkIdent(Context context) {

        if (MyAppLication.getRealnameStatus() == 3) {//已实名认证
            return true;
        } else if (MyAppLication.getRealnameStatus() == 2) {//审核中
            showApplyTip(getContext(), App.INSTANCE.getString(R.string.strBaseActivity201), false);
            return false;
        } else if (MyAppLication.getRealnameStatus() == 4) {//被拒绝
            VerifyHomeActivity.start(getContext());
            return false;
        } else {
            showApplyTip(getContext(), App.INSTANCE.getString(R.string.strBaseActivity204), true);
            return false;
        }

    }

    /**
     * 判断用户实名认证弹窗
     */
    private void showApplyTip(Context mcontext, String msg, boolean status) {
        AlertDialog tipDialog = new AlertDialog.Builder(mcontext)
                .setTitle(App.INSTANCE.getString(com.sskj.gocoin.R.string.strBaseFragment210))
                .setMessage(msg)
                .setPositiveButton(status ? App.INSTANCE.getString(com.sskj.gocoin.R.string.strBaseFragment211) : App.INSTANCE.getString(com.sskj.gocoin.R.string.strBaseFragment212), (dialog, which) -> {
                    dialog.dismiss();
                    if (status) {
                        openActivity(VerifyJuniorActivity.class, VERIFY_IDENT_CODE);
                    }
                })
                .setNegativeButton(App.INSTANCE.getString(com.sskj.gocoin.R.string.strBaseFragment213), (dialog, which) -> dialog.dismiss())
                .create();
        tipDialog.show();

    }

    protected void openActivity(Class<? extends Activity> clz, int requestCode) {
        if (MyAppLication.isLogin()) {
            startActivityForResult(new Intent(getActivity(), clz), requestCode);
        } else {
            ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
            getActivity().overridePendingTransition(com.sskj.gocoin.R.anim.lib_anim_in, com.sskj.gocoin.R.anim.lib_anim_out);
        }
    }

    @Override
    public void initData() {
        mPresenter.getPayInfo();
    }

    public void onGetPayInfo(PayInInfoBean payInInfoBean) {
        isEnable = true;
        this.payInInfoBean = payInInfoBean;
        etFragmentPayInMoney.setHint(getString(R.string.app_payInFragment1) + payInInfoBean.getBuy_min() + getString(R.string.my_yuan));
        minBuy = Double.parseDouble(payInInfoBean.getBuy_min());

    }

    public void onPayWaySuccess(HttpData<List<PayWayBean>> body) {
        mAdapter.setNewData(body.getData());
    }

    /**
     * 当支付方式开关切换成功
     *
     * @param item
     */
    public void onChangeSwitchSuccess(PayWayBean item) {
        mAdapter.notifyDataSetChanged();
    }

    public void getUrlSuccess(String info) {

        WebViewActivity.start(getContext(), info);
    }

    public void onGetpayInfoFail(String msg) {
        this.msg = msg;
        isEnable = false;
    }
}
